package one.stand.service.impl;

import one.stand.advice.ResultEnum;
import one.stand.mapper.AddressMapperExt;
import one.stand.model.Address;
import one.stand.service.AddressService;
import one.stand.util.AssertUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author cjr
 */
@Service
public class AddressServiceImpl implements AddressService {
    @Autowired
    private AddressMapperExt addressMapperExt;

    @Override
    public void save(Address addressModel) {
        AssertUtil.nonNull(addressModel.getReceiveName(), ResultEnum.PARAM_CHECK, "收货人姓名不能为空");
        AssertUtil.nonNull(addressModel.getReceivePhone(), ResultEnum.PARAM_CHECK, "收货人电话不能为空");
        AssertUtil.isFalse(StringUtils.isBlank(addressModel.getDetailedAddress()) || StringUtils.isBlank(addressModel.getLocationAddress()), ResultEnum.PARAM_CHECK, "要输入完整的地址哦 亲~!");

        if (Objects.isNull(addressModel.getAddressId())) {
            AssertUtil.nonNull(addressModel.getUserId(), ResultEnum.PARAM_CHECK);

            Address list = addressMapperExt.selectDefault(addressModel.getUserId());
            addressModel.setIsDefault(Objects.isNull(list) ? 1 : 0);
            addressModel.setCreateTime(new Date());
            addressModel.setIsDel(0);
            addressMapperExt.insertSelective(addressModel);
        } else {
            addressModel.setUserId(null);
            addressMapperExt.updateByPrimaryKeySelective(addressModel);
        }
    }

    @Override
    public void remove(Integer id) {
        addressMapperExt.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional
    public void setDefault(Integer id) {
        Address addressModelSelect = addressMapperExt.selectByPrimaryKey(id);

        int r = addressMapperExt.updateIsdefault(addressModelSelect.getUserId());
        if (r > 0) {
            Address addressModel = new Address();
            addressModel.setAddressId(id);
            addressModel.setIsDefault(1);
            addressMapperExt.updateByPrimaryKeySelective(addressModel);
        }
    }

    @Override
    public List<Address> list(Integer userId) {
        return addressMapperExt.select(userId);
    }

    @Override
    public Address getDefault(Integer userId) {
        return addressMapperExt.selectDefault(userId);
    }
}
